package com.ly.mp.busicen.rule.extention.auto;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import com.ly.mp.busicen.rule.extention.annotation.XruleFlow;
import com.ly.mp.busicen.rule.extention.annotation.XruleScan;

public class XruleScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

	private static final Logger log = LoggerFactory.getLogger(XruleScannerRegistrar.class);

	private ResourceLoader resourceLoader;

	private Environment environment;

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		log.info("Xrule registry ");
		AnnotationAttributes annoAttrs = AnnotationAttributes
				.fromMap(importingClassMetadata.getAnnotationAttributes(XruleScan.class.getName()));
		String[] packages = annoAttrs.getStringArray("packages");
		ClassPathXruleScanner scanner = new ClassPathXruleScanner(registry, XruleFlow.class);
		scanner.setResourceLoader(resourceLoader);
		scanner.setEnvironment(environment);
		scanner.registerDefaultFilters();
		scanner.doScan(packages);
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}

}
